package basic

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"project/controller"
	"project/mySql"
)

/**
 * @File : user.go
 * @Description : 处理用户数据，实现登录、注册功能
 * @Author : 吴概
 * @Date : 2023/2/6
 */

// UserLoginResponse 登录功能的返回
type UserLoginResponse struct {
	controller.Response
	UserId int64  `json:"user_id"`
	Token  string `json:"token"`
}

// UserResponse 用户信息的返回
type UserResponse struct {
	controller.Response
	User controller.User `json:"user"`
}

// Login 登录功能
func Login(c *gin.Context) {
	email := c.Query("username")
	password := c.Query("password")
	current := mySql.GetUserByToken(email)
	if current.Id != 0 {
		if current.Password == password {
			c.JSON(http.StatusOK, UserLoginResponse{
				Response: controller.Response{StatusCode: 0},
				UserId:   current.Id,
				Token:    email,
			})
		} else {
			c.JSON(http.StatusOK, UserLoginResponse{
				Response: controller.Response{StatusCode: 1, StatusMsg: "Password error"},
			})
		}
	} else {
		c.JSON(http.StatusOK, UserLoginResponse{
			Response: controller.Response{StatusCode: 1, StatusMsg: "User doesn't exist"},
		})
	}
}

// Register 注册功能
func Register(c *gin.Context) {
	email := c.Query("username")
	password := c.Query("password")
	//账号密码不能过长（大于24）
	if len(email) > 24 || len(password) > 24 {
		c.JSON(http.StatusOK, UserLoginResponse{
			Response: controller.Response{StatusCode: 1, StatusMsg: "账号或密码过长"},
		})
	}
	if mySql.GetUserByToken(email).Id == 0 { //当Id=0时证明数据库中没有此项
		mySql.NewUsersData(controller.User{
			Name:     mySql.GetDefaultUserName(),
			Token:    email,
			Password: password,
		})
		id := mySql.GetUserByToken(email).Id
		c.JSON(http.StatusOK, UserLoginResponse{
			Response: controller.Response{StatusCode: 0},
			UserId:   id,
			Token:    email,
		})
	} else {
		c.JSON(http.StatusOK, UserLoginResponse{
			Response: controller.Response{StatusCode: 1, StatusMsg: "User Registed"},
		})
	}
}

// ReturnUserInfo 返回用户信息
func ReturnUserInfo(c *gin.Context) {
	id := controller.ParseInt(c.Query("user_id"))
	token := c.Query("token")
	current := mySql.GetUser(id)
	if current.Token == token {
		c.JSON(http.StatusOK, UserResponse{
			Response: controller.Response{StatusCode: 0},
			User:     mySql.GetUser(current.Id),
		})
	} else {
		c.JSON(http.StatusOK, UserResponse{
			Response: controller.Response{StatusCode: 1, StatusMsg: "id与账号不对应"},
		})
	}
}
